<template>
  <li>
    <span v-if="!isEditing">{{ todo }}</span>
    <input v-else v-model="editedTodo" @keyup.enter="saveTodo" />

    <button @click="toggleEdit">
      {{ isEditing ? 'Cancel' : 'Edit' }}
    </button>
    <button @click="saveTodo" v-if="isEditing">Save</button>
    <button @click="removeTodo">Remove</button>
  </li>
</template>

<script setup>
import { ref } from 'vue';

// 接收 props
const props = defineProps({
  todo: String,
  index: Number
});

const emit = defineEmits(['remove-todo', 'update-todo']);

const isEditing = ref(false);
const editedTodo = ref(props.todo);

function toggleEdit() {
  isEditing.value = !isEditing.value;
  editedTodo.value = props.todo; // 恢复原始值
}

function saveTodo() {
  if (editedTodo.value.trim()) {
    emit('update-todo', { index: props.index, newTodo: editedTodo.value.trim() });
    isEditing.value = false;
  }
}
function removeTodo() {
  emit('remove-todo', props.index);
}
</script>

<style scoped>
li {
  display: flex;
  align-items: center;
  margin: 5px 0;
}

li button {
  margin-left: 10px;
  background-color: #90EE90; /* 修改为绿色背景 */
  border: none;
  border-radius: 5px;
}

li button:hover {
  background-color: #76C7C0; /* 悬停时的绿色背景 */
}
</style>